import numpy as np


def train_test_split(X, y, test_ratio, seed=None):
    """
    将数据 X 和 y 按照test_ratio分割成X_train, X_test, y_train, y_test
    :param X: 特征值
    :param y: 标签
    :param test_ratio: 测试数据集百分比
    :param seed: 随机数种子
    :return:
    """
    assert X.shape[0] == y.shape[0], \
        "the size of X must be equal to the size of y"
    assert 0.0 <= test_ratio <= 1.0, \
        "test_ration must be valid"
    # 如果有随机种子，就设置，这样保证当用户传相同的随机种子值，会返回相同的结果
    if seed:
        np.random.seed(seed)
    # 根据特征值生成对应的随机索引
    shuffled_indexes = np.random.permutation(len(X))

    # 获取测试集数据大小
    test_size = int(len(X) * test_ratio)
    # 获取测试和训练数据集索引数组
    test_indexes = shuffled_indexes[:test_size]
    train_indexes = shuffled_indexes[test_size:]

    # 获取分离后的测试和训练数据集
    X_train = X[train_indexes]
    y_train = y[train_indexes]

    X_test = X[test_indexes]
    y_test = y[test_indexes]
    return X_train, y_train, X_test, y_test